package cn.cat.main.executors;

import java.util.concurrent.*;

public class ExecutorCallableTest1 {

    public static void main(String[] args) {
        //通过ExecutorCompletionService实现任务结果的获取，可以实现将完成的任务先获取。按照这些任务的完成的时间顺序来处理他们的结果。
        //创建一个线程池
        ExecutorService pools = Executors.newFixedThreadPool(5);
        ExecutorCompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(pools);
        //创建多个有返回值的任务
        for(int i = 0 ; i <= 10 ; i++){
            completionService.submit(new Task1(i));
        }
        for(int i = 0 ; i <= 10 ; i++){
            try {
                Future<Integer> f = completionService.take();
                System.out.println(f.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
        pools.shutdown();

    }
}
class Task1 implements Callable<Integer>{
    private Integer taskID;
    public Task1(Integer taskID) {
        this.taskID = taskID;
    }
    public Integer call() throws Exception {
        if(taskID.equals(3))
            Thread.sleep(10000);
        System.out.println("任务["+taskID+"]开始执行");
        return taskID;
    }
}
